package m3;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;

public class Producer {
//    “事务消息生产者”




//    nameserver
//    设置监听器
//    启动
    public static void main(String[] args) throws MQClientException {
        TransactionMQProducer producer= new TransactionMQProducer("tranmq-1");
        producer.setNamesrvAddr("192.168.64.141:9876");

        ConcurrentHashMap<String,LocalTransactionState> map=new ConcurrentHashMap<>();

        producer.setTransactionListener(new TransactionListener() {
            @Override
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {
                System.out.println("本地事务");
                if (Math.random()<0.3){
                    System.out.println("网络故障");
                    map.put(message.getTransactionId(), LocalTransactionState.UNKNOW);
                    return LocalTransactionState.UNKNOW;
                }


                if (Math.random()<0.5){
                    System.out.println("成功");
                    return LocalTransactionState.COMMIT_MESSAGE;
                }else {
                    System.out.println("失败");
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }
            }

            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
//                只要是unknown就会执行回查
                System.out.println("我要回查");
                return map.get(messageExt.getTransactionId());
            }
        });
        producer.start();
        Message m=new Message();

        while (true){
            System.out.println("enter:");
            String s=new Scanner(System.in).nextLine();
            Message msg=new Message("Topic3",s.getBytes());
            TransactionSendResult r=producer.sendMessageInTransaction(msg, null);
            System.out.println("完成："+r);
        }

    }
}
